package OrderedwaterMark;

import bean.WaterSensor;
import org.apache.flink.api.common.eventtime.*;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.util.Arrays;


/**
 * @author Spring_Hu
 * @date 2021/10/14 18:22
 */
public class UserDefinedOutOfOrderedWaterMark {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

       env.setParallelism(1);


        SingleOutputStreamOperator<WaterSensor> source = env.socketTextStream("localhost", 8888)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                });


        SingleOutputStreamOperator<WaterSensor> wso = source.assignTimestampsAndWatermarks(WatermarkStrategy.
                <WaterSensor>forGenerator(new WatermarkGeneratorSupplier<WaterSensor>() {
                    @Override
                    public WatermarkGenerator<WaterSensor> createWatermarkGenerator(Context context) {
                        return new WatermarkGenerator() {
                            long outOfOrdernessMillis=3000L;
                            long maxTimestamp=Long.MIN_VALUE + outOfOrdernessMillis;
                            @Override
                            public void onEvent(Object event, long eventTimestamp, WatermarkOutput output) {
                                maxTimestamp = Math.max(maxTimestamp, eventTimestamp);
                            }

                            @Override
                            public void onPeriodicEmit(WatermarkOutput output) {
                                output.emitWatermark(new Watermark(maxTimestamp - outOfOrdernessMillis));
                            }
                        };
                    }
                }).
                withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                    @Override
                    public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                        return element.getTs() * 1000L;
                    }
                })).setParallelism(1);


        wso.keyBy(value -> value.getId()).window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
                    @Override
                    public void process(String s, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                        System.out.println("window大小["+context.window().getStart()+","+context.window().getEnd()+")");
                        System.out.println("当前的Watermark:"+context.currentWatermark());
                        out.collect(Arrays.asList(elements).toString());
                    }
                }).print();

        env.execute();
    }
}
